#!/bin/bash

CWD=`readlink -f .`
BASE_DIR=`readlink -f $1`
OUT_DIR=`readlink -f $2`
PROC=$3
REF_GENOME=/home/Reference_Genome/Homo_sapiens/UCSC/hg19/Sequence/Bowtie2Index/genome
RRNA=/home/Reference_Genome/Homo_sapiens/UCSC/hg19/Annotation/rRNA/Bowtie2Index/rRNA
echo "Input directory is ${BASE_DIR}"
echo "Output directory is ${OUT_DIR}"

SUFFIX=.fq.gz

cd $BASE_DIR
if [[ -d $OUT_DIR ]] then
    rm -rf $OUT_DIR;
fi

mkdir -p ${OUT_DIR}/clean

fastp -i *1${SUFFIX} -I *2${SUFFIX} \
    -o ${OUT_DIR}/clean/R1.fastq.gz -O ${OUT_DIR}/clean/R2.fastq.gz \
    --detect_adapter_for_pe \
    --umi --umi_loc=per_read --umi_len=6 \
    -w 30 -c --overlap_len_require 15 \
    --html ${OUT_DIR}/clean/fastp_report.html

cd $OUT_DIR
cd clean
bowtie2 --local --very-fast-local -p ${PROC} --un-conc unrRNA.fq -x ${RRNA} -1 R1.fastq.gz -2 R2.fastq.gz -S map.sam && rm -rf map.sam 
cd ../

# mkdir map
bowtie2 --local --very-sensitive-local -p ${PROC} -x ${REF_GENOME} \
    -1 clean/unrRNA.1.fq -2 clean/unrRNA.2.fq -S map/map.sam

cd map
samtools view -b -o map.bam -f 2 -q 10 -x XS -h -S map.sam && rm -rf map.sam
samtools sort -o sort.bam map.bam && samtools index sort.bam && rm -rf map.bam 
umi_tools dedup -I sort.bam --umi-separator=":" --paired -S ddup.bam && rm -rf sort.bam*
samtools index ddup.bam 

cd $CWD





